package com.molyfun.parents.activity.setting;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.account.DebugModeActivity;
import com.molyfun.parents.activity.account.LoginActivity;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.fragment.dialog.CommonChooseDialogFragment;
import com.molyfun.parents.rest.bean.ThirdUnboundResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.DBManager;
import com.molyfun.parents.utils.FileUtils;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.yilin.parents.wxapi.WXEntryActivity;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MineSettingActivity extends BaseActivity implements View.OnClickListener, UIEventListener {

    @InjectView(R.id.logout_layout)
    LinearLayout mLogout;
    @InjectView(R.id.change_account_layout)
    LinearLayout mChangeAccountLayout;
    @InjectView(R.id.e_email_layout)
    LinearLayout mE_EmailLayout;
    @InjectView(R.id.modification_password_layout)
    LinearLayout mModificationPasswordLayout;
    @InjectView(R.id.suggestion_layout)
    LinearLayout mSuggestionLayout;
    @InjectView(R.id.version_layout)
    LinearLayout mVersionLayout;
    @InjectView(R.id.about_layout)
    LinearLayout mAboutLayout;
    @InjectView(R.id.clear_layout)
    LinearLayout mClearLayout;
    @InjectView(R.id.current_account)
    TextView mCurrent_account;//当前账户
    @InjectView(R.id.binding_wx)
    TextView mBindingWX;
    @InjectView(R.id.unbound)
    TextView mUnboundWX;
    @InjectView(R.id.base_title_left)
    ImageView mTitleLeft;
    @InjectView(R.id.base_title)
    TextView mTitle;
    @InjectView(R.id.wx_binding_layout)
    LinearLayout mWxBindingLayout;
    @InjectView(R.id.wx_layout)
    LinearLayout mWxLayout;
    @InjectView(R.id.debug_layout)
    LinearLayout mDebugLayout;
    @InjectView(R.id.debug_close)
    TextView mDebugClose;

    public static void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context, MineSettingActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_setting);

        ButterKnife.inject(this);

        getSupportActionBar().setTitle("");

        mLogout.setOnClickListener(this);
        mSuggestionLayout.setOnClickListener(this);
        mVersionLayout.setOnClickListener(this);
        mAboutLayout.setOnClickListener(this);
        mClearLayout.setOnClickListener(this);
        mChangeAccountLayout.setOnClickListener(this);
        mE_EmailLayout.setOnClickListener(this);
        mModificationPasswordLayout.setOnClickListener(this);
        mCurrent_account.setText(PreferencesStorageUtil.getPhoneNum(this));
        if (PreferencesStorageUtil.getThirdBindingStatu(this).equals("1")) {
            mUnboundWX.setText("解绑");
            mWxLayout.setVisibility(View.VISIBLE);
        } else {
            mUnboundWX.setText("未绑定");
            mWxLayout.setVisibility(View.GONE);
        }
        mBindingWX.setText(PreferencesStorageUtil.getThirdAccount(this));
//        mUnboundWX.setOnClickListener(this);
        mWxBindingLayout.setOnClickListener(this);
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_SETTING_MOLIFICATION_ACCOUNT, this);
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_BIND_WX, this);

        mTitleLeft.setOnClickListener(this);
        mTitle.setText("设置");
        mDebugLayout.setOnClickListener(this);
        mDebugClose.setOnClickListener(this);

    }

    @Override
    protected void onDestroy() {
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_SETTING_MOLIFICATION_ACCOUNT, this);
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_BIND_WX, this);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
            case R.id.logout_layout:

                new CommonChooseDialogFragment.CommonChooseDialogBuilder("您确定要退出吗？")
                        .setCommonChooseDialogClickListener(new CommonChooseDialogFragment.CommonChooseDialogClickListener() {
                            @Override
                            public void onConfirm() {
//                                clearData();
                                if (!JPushInterface.isPushStopped(MineSettingActivity.this)) {
                                    JPushInterface.stopPush(MineSettingActivity.this);
                                }
                                PreferencesStorageUtil.logout(MineSettingActivity.this);
                                Intent intent = new Intent(MFPApplication.getInstance(), LoginActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                MFPApplication.getInstance().startActivity(intent);
                                com.molyfun.parents.utils.ActivityManager.getInstance().logout();
                            }

                            @Override
                            public void onCancel() {
                            }
                        })
                        .build(getSupportFragmentManager().beginTransaction());


                break;
            case R.id.change_account_layout:
                MolificationAccountActivity.startActivity(this);
                break;
            case R.id.e_email_layout:
                //TODO 电子邮箱
                EEmailActivity.startActivity(this);
                break;
            case R.id.modification_password_layout:
                MolificationPasswordActivity.startActivity(this);
                break;
            case R.id.suggestion_layout:

                SuggestionActivity.startActivity(this);

                break;
            case R.id.debug_layout:
                DebugModeActivity.startActivity(MineSettingActivity.this);
                break;

            case R.id.debug_close:
                PreferencesStorageUtil.setDebugMode(this, false);
                mDebugLayout.setVisibility(View.GONE);
                break;

            case R.id.version_layout:

                UpdateActivity.startActivity(this);

                break;

            case R.id.about_layout:

//                WebViewActivity.startActivity(getActivity(), "http://www.baidu.com", "关于我们");
                AboutActivity.startActivity(this);
                break;

            case R.id.clear_layout:

                new CommonChooseDialogFragment.CommonChooseDialogBuilder("将删除图片缓存,以及其他为您的本地数据，确定要删除吗?")
                        .setCommonChooseDialogClickListener(new CommonChooseDialogFragment.CommonChooseDialogClickListener() {
                            @Override
                            public void onConfirm() {
                                clearData();
                                toast("清除成功");
                            }

                            @Override
                            public void onCancel() {

                            }
                        })
                        .build(getSupportFragmentManager().beginTransaction());


                break;
            case R.id.wx_binding_layout:
                if (PreferencesStorageUtil.getThirdBindingStatu(this).equals("1")) {
                    new CommonChooseDialogFragment.CommonChooseDialogBuilder("您将要解绑当前已绑定的微信账号："+PreferencesStorageUtil.getThirdAccount(this)+"，您确定要进行解绑操作吗？").setCommonChooseDialogClickListener(new CommonChooseDialogFragment.CommonChooseDialogClickListener() {
                        @Override
                        public void onConfirm() {
                            loadDataUnboundWXU();
                        }

                        @Override
                        public void onCancel() {

                        }
                    }).build(getSupportFragmentManager().beginTransaction());
                    break;
                } else {
                    WXEntryActivity.bindWeixin(MineSettingActivity.this, MFPApplication.sApi);
                }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(PreferencesStorageUtil.isDebugMode(this)){
            mDebugLayout.setVisibility(View.VISIBLE);
        }else{
            mDebugLayout.setVisibility(View.GONE);
        }

    }

    private void loadDataUnboundWXU() {
        Call<ThirdUnboundResponse> call = MFPApplication.getInstance().getRestClient().unboundThird(PreferencesStorageUtil.getThirdOpenId(this));
        call.enqueue(new Callback<ThirdUnboundResponse>() {
            @Override
            public void onResponse(Call<ThirdUnboundResponse> call, Response<ThirdUnboundResponse> response) {
                if (response.body() != null && response.body().getMsg() != null) {
                    if (response.body().getData() != null) {
                        if (!TextUtils.isEmpty(response.body().getData().getStatus()) && response.body().getData().getStatus().equals("0")) {
                            toast("解绑成功");
                            PreferencesStorageUtil.setThirdAccount(MineSettingActivity.this,response.body().getData().getUsername()+"");
                            PreferencesStorageUtil.setThirdOpenId(MineSettingActivity.this,response.body().getData().getOpenid()+"");
                            PreferencesStorageUtil.setThirdBindingStatu(MineSettingActivity.this,response.body().getData().getStatus()+"");
                            if (PreferencesStorageUtil.getThirdBindingStatu(MineSettingActivity.this).equals("1")) {
                                mUnboundWX.setText("解绑");
                            } else {
                                mUnboundWX.setText("未绑定");
                                mWxLayout.setVisibility(View.GONE);
                            }
                            mBindingWX.setText(PreferencesStorageUtil.getThirdAccount(MineSettingActivity.this));
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ThirdUnboundResponse> call, Throwable t) {

            }
        });

    }

    private void clearData() {
        FileUtils.deleteFile();
//        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
//        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
//        DaoSession daoSession = daoMaster.newSession();
//        daoSession.getHomeworkDBDao().deleteAll();
        DBManager.getInstance(MFPApplication.getInstance()).deleSQL();
    }


    @Override
    public void handleUIEvent(Message msg) {

        switch (msg.what){
            case EventDispatcherEnum.UI_EVENT_SETTING_MOLIFICATION_ACCOUNT:
                finish();
                break;
            case EventDispatcherEnum.UI_EVENT_BIND_WX:
                if (PreferencesStorageUtil.getThirdBindingStatu(this).equals("1")) {
                    mUnboundWX.setText("解绑");
                    mBindingWX.setText(PreferencesStorageUtil.getThirdAccount(this));
                    mWxLayout.setVisibility(View.VISIBLE);
                } else {
                    mUnboundWX.setText("未绑定");
                    mWxLayout.setVisibility(View.GONE);
                }
                break;
        }
    }
}
